<template>
  <el-dialog v-el-drag-dialog title="课时管理" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose">
    <el-card style="margin:0 0 5px 5px" shadow="none">
      <div slot="header" class="clearfix">
        <el-button class="m-b-20" type="text" style="color: black; font-weight: bold;">{{ form.courseName }}</el-button>
        <el-button style="float: right;" class="m-l-20" type="primary" plain size="small" @click="onSubmit">保存</el-button>
        <br>
        <el-button type="success" round size="small" @click="addChapter">添加章节</el-button>
      </div>
      <div v-for="(c, c_index) in form.chapters" :key="'c_' + c_index" class="text item">
        <el-row>
          <el-input v-model="c.chapterName" class="width-200" placeholder="章节名称" />
          <el-button style="float: right" type="danger" round size="small" @click="deleteChapter(c_index)">删除章节</el-button>
          <el-button style="float: right; margin-right: 20px;" type="primary" round size="small" @click="addHour(c.chapterName)" :disabled="c.chapterName == undefined">添加课时</el-button>
        </el-row>
        <el-card style="margin:5px" shadow="always">
          <el-table
            :data="c.hours"
            :show-header="false"
            style="width: 100%"
            empty-text="请添加课时"
          >
            <el-table-column align="left" prop="hourId" label="">
              <template slot-scope="scope">
                <i class="el-icon-video-play m-r-20"></i>
                {{ scope.row.title }}
                <i class="el-icon-delete red" style="float: right;" @click="deleteHour(c.chapterName, scope.row.title)"></i>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-divider />
      </div>
    </el-card>

    <training-resource-table-dialog v-if="openResourceTableDialog" ref="resource_table_dialog" :exclude="resourceIds" @confirmDialog="setHour" />
  </el-dialog>
</template>

<script>
import { courseInfo, courseHourSave } from '@/api/training/course'
import TrainingResourceTableDialog from '@/views/training/resource/table/dialog'
import {modelLatest} from "@/api/tool/workflow";

export default {
  name: 'TrainingHourFormDialog',
  components: {
    TrainingResourceTableDialog
  },
  data() {
    return {
      visible: false,
      appendToBody: false,
      form: {
        courseId: undefined,
        courseName: undefined,
        chapters: []
      },
      currentChapterName: undefined,
      openResourceTableDialog: false,
      resourceIds: undefined,
      hasChanged: false
    }
  },
  methods: {
    init(id) {
      this.hasLoaded = false
      this.form.courseId = id || null
      this.visible = true
      this.$nextTick(() => {
        this.loadForm(id)
      })
    },
    loadForm(id) {
      courseInfo(id).then(response => {
        this.form = this.$api.objectUpdate(this.form, response.param)
        this.form.chapters.forEach(chapter => {
          chapter.hours.forEach(hour => {
            this.resourceIds += ',' + hour.resourceId
          })
        })
        if (this.resourceIds && this.resourceIds.length > 0) {
          this.resourceIds = this.resourceIds.substring(1)
        }
        if (this.form.chapters.length === 0) {
          this.form.chapters.push({
            courseId: this.form.courseId,
            chapterId: undefined,
            chapterName: undefined,
            hours: []
          })
        }
      }).catch(() => {
      })
    },
    addChapter() {
      this.form.chapters.push({
        courseId: this.form.courseId,
        chapterId: undefined,
        chapterName: undefined,
        hours: []
      })
      this.hasChanged = true
    },
    deleteChapter(index) {
      this.form.chapters.splice(index, 1)
      this.hasChanged = true
    },
    addHour(chapterName) {
      this.currentChapterName = chapterName
      this.openResourceTableDialog = true
      this.$nextTick(() => {
        this.$refs.resource_table_dialog.init()
      })
    },
    setHour(resources) {
      let courseId = this.form.courseId
      let chapterName = this.currentChapterName
      let chapterIndex = this.form.chapters.findIndex(function(chapter) {
        return chapter.chapterName === chapterName
      })
      let chapter = this.form.chapters.filter(chapter => {
        return chapter.chapterName === chapterName
      })

      for (let i in resources) {
        chapter[0].hours.push({
          courseId: courseId,
          chapterId: undefined,
          hourId: undefined,
          resourceId: resources[i].resourceId,
          title: resources[i].name,
          type: resources[i].type,
          duration: resources[i].duration
        })
      }

      this.form.chapters.splice(chapterIndex, 1, chapter[0])
      this.currentChapterName = undefined
      this.hasChanged = true
    },
    deleteHour(chapterName, title) {
      let chapterIndex = this.form.chapters.findIndex(function(chapter) {
        return chapter.chapterName === chapterName
      })
      let chapter = this.form.chapters.filter(chapter => {
        return chapter.chapterName === chapterName
      })
      let index = chapter[0].hours.findIndex(function(hour) {
        return hour.title === title
      })
      chapter[0].hours.splice(index, 1)
      this.form.chapters.splice(chapterIndex, 1, chapter[0])
      this.hasChanged = true
    },
    onSubmit() {
      courseHourSave(this.form).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.hasChanged = false
        this.onClose()
      }).catch(() => {
      })
    },
    onClose() {
      if (this.hasChanged) {
        this.$modal.confirm('数据有变化，是否提交数据？').then(() => {
          this.onSubmit()
        }).catch(() => {
          this.hasChanged = false
          this.form = {
            courseId: undefined,
            courseName: undefined,
            chapters: []
          }
          this.visible = false
        })
      } else {
        this.form = {
          courseId: undefined,
          courseName: undefined,
          chapters: []
        }
        this.visible = false
      }
    }
  }
}
</script>
